package game.zqll;

import com.artemis.BaseSystem;
import com.artemis.World;
import com.artemis.WorldConfigurationBuilder;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.kotcrab.vis.ui.VisUI;
import game.zqll.systems.*;

import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

import static com.artemis.WorldConfigurationBuilder.Priority.HIGH;

public class ModSampleApplication extends ApplicationAdapter {

    // 核心ECS世界
    private World world;
    private WorldConfigurationBuilder configBuilder;
    private AssetManager assetManager;
    public static final int worldWidth = 600;
    public static final int worldHeight = 480;

    @Override
    public void create() {
        // 初始化ECS世界
        VisUI.load();
        OrthographicCamera camera = new OrthographicCamera();
        configBuilder = new WorldConfigurationBuilder()
            .with(new Mappers())
            .with(new CameraSystem(camera))
            .with(new SpawnSystem())
            .with(new MoveSystem())
            .with(HIGH, new ClearScreenSystem())
            .with(new BorderRenderSystem())
            .with(new GuiSystem())
        ;
        assetManager = new AssetManager();
        initializeAndLoadGameMod(configBuilder, assetManager);

        world = new World(configBuilder.build().register("camera", camera));

        for (BaseSystem system : world.getSystems()) {
            System.out.println("注册了系统: " + system.getClass().getName());
        }
    }

    private void initializeAndLoadGameMod(WorldConfigurationBuilder configBuilder, AssetManager assetManager) {
        // 获取项目根路径
        String projectRootPath = System.getProperty("user.dir");
        // 拼接 mods 文件夹路径
        String modsFolderPath = projectRootPath + File.separator + "mods";
        // 创建 File 对象表示 mods 文件夹
        File modsFolder = new File(modsFolderPath);
        // 定义 jar 文件过滤器
        FileFilter jarFilter = file -> file.isFile() && file.getName().endsWith(".jar");
        // 获取 mods 文件夹中所有 jar 文件
        File[] jarFiles = modsFolder.listFiles(jarFilter);

        final List<GameMod> allMods = new ArrayList<>();
        if (jarFiles != null) {
            // 遍历并输出 jar 文件路径
            for (File jarFile : jarFiles) {
                System.out.println("加载mod文件，路径: " + jarFile.getAbsolutePath());
                allMods.addAll(ModLoader.loadMod(jarFile));
            }
        } else {
            System.out.println("未找到 mods 文件夹或者 mods 文件夹中没有 jar 文件");
        }

        allMods.forEach(mod -> {
            mod.initialize(configBuilder);
            mod.loadResources(assetManager);
        });
    }

    @Override
    public void render() {
        // 启动游戏循环
        world.setDelta(Gdx.graphics.getDeltaTime());
        world.process();
    }

    @Override
    public void resize(int width, int height) {
        world.getSystem(CameraSystem.class).getViewport().update(width, height, true);
        world.getSystem(GuiSystem.class).getStage().getViewport().update(width, height, true);
    }

    public static class ModLoader {

        public static List<GameMod> loadMod(File jarFile) {
            List<GameMod> mods = new ArrayList<>();
            ClassLoader originalLoader = Thread.currentThread().getContextClassLoader();
            try {
                URLClassLoader modLoader = new URLClassLoader(
                    new URL[]{jarFile.toURI().toURL()},
                    ModLoader.class.getClassLoader()
                );
                Thread.currentThread().setContextClassLoader(modLoader);

                ServiceLoader<GameMod> serviceLoader = ServiceLoader.load(GameMod.class);
                for (GameMod mod : serviceLoader) {
                    mods.add(mod);
                }
            } catch (Exception e) {
                Gdx.app.error("ModLoader", "加载失败: " + jarFile, e);
            } finally {
                Thread.currentThread().setContextClassLoader(originalLoader);
            }
            return mods;
        }
    }
}
